package api

import (
	"company_website/src/global"
	"company_website/src/model"
	"company_website/src/model/common"
	"company_website/src/model/request"
	"company_website/src/model/response"
	"company_website/src/server"
	"github.com/gin-gonic/gin"
)

type Item struct {
}

func (i Item) GetItemInfoList(c *gin.Context) {
	reqInfo := &common.GetPageInfo{}
	if err := c.ShouldBindJSON(&reqInfo); err != nil {
		global.GVL_LOG.Error("接受参数失败", err)
		response.FailWithMessage("接受参数失败", c)
		return
	}
	//到数据库中查找数据
	resInfo, err := server.ItemServer.GetAllItemInfoPage(reqInfo)
	if err != nil {
		global.GVL_LOG.Error("获取项目失败", err)
		response.FailWithMessage("获取项目失败", c)
		return
	}
	response.OkWithData(resInfo, c)
}

// GetItemInfo 输入标题查询项目
func (i Item) GetItemInfo(c *gin.Context) {
	var itemRequest request.GetItemInfo
	if err := c.ShouldBindJSON(&itemRequest); err != nil {
		response.FailWithMessage("获取标题错误", c)
		return
	}
	var itemResponse []*model.Item
	err := global.GVL_DB.Model(&model.Item{}).Where("title like ?", "%"+itemRequest.Title+"%").Find(&itemResponse).Error
	if err != nil {
		response.FailWithMessage("查询错误", c)
		return
	}
	response.OkWithData(itemResponse, c)
}
func (i Item) ItemAdd(c *gin.Context) {
	var itemRequest request.ItemInfo
	if err := c.ShouldBindJSON(&itemRequest); err != nil {
		response.FailWithMessage("获取添加信息错误", c)
		return
	}
	itemResponse := &model.Item{
		Id:      itemRequest.Id,
		Title:   itemRequest.Title,
		Content: itemRequest.Content,
		People:  itemRequest.People,
		Time:    server.ServerComment.GetUnixTime(),
	}
	err := global.GVL_DB.Model(&model.Item{}).Create(itemResponse).Error
	if err != nil {
		response.FailWithMessage("添加项目失败", c)
		return
	}
	response.OkWithData("添加项目成功", c)
}
func (i Item) ItemDelete(c *gin.Context) {
	var itemRequest request.ItemDel
	if err := c.ShouldBindJSON(&itemRequest); err != nil {
		response.FailWithMessage("获取删除信息错误", c)
		return
	}
	var itemInfo model.Item
	err := global.GVL_DB.Model(&model.Item{}).Where("id = ?", itemRequest.Id).Delete(itemInfo).Error
	if err != nil {
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithData("删除成功", c)
}

func (i Item) ItemModify(c *gin.Context) {
	var itemRequest request.ItemInfo
	if err := c.ShouldBindJSON(&itemRequest); err != nil {
		response.FailWithMessage("获取修改信息错误", c)
		return
	}
	itemResponse := &model.Item{
		Id:      itemRequest.Id,
		Title:   itemRequest.Title,
		Content: itemRequest.Content,
		People:  itemRequest.People,
		Time:    server.ServerComment.GetUnixTime(),
	}
	err := global.GVL_DB.Model(&model.Item{}).Where("id = ?", itemRequest.Id).Updates(itemResponse).Error
	if err != nil {
		response.FailWithMessage("修改失败", c)
		return
	}
	response.OkWithData("修改成功", c)
}
